package com.qst.crop.demo.controller;

import com.qst.crop.demo.common.Result;
import com.qst.crop.demo.entity.Browse;
import com.qst.crop.demo.entity.Product;
import com.qst.crop.demo.entity.User;
import com.qst.crop.demo.service.BrowseService;
import com.qst.crop.demo.service.ProductService;
import com.qst.crop.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/brow")
@CrossOrigin(origins = "*")
public class BrowseController {

    @Autowired
    BrowseService browseService;
    @Autowired
    ProductService productService;
    @Autowired
    UserService userService;

    /**
     *  添加商品浏览记录
     * @param email
     * @param product
     * @return
     */
    @RequestMapping("/add")
    public Result addFavorite(String email, Product product){
        System.out.println("添加商品浏览记录");

        if(product == null || product.getProductId() < 0){
            return Result.fail(-1, "无效参数");
        }

        User userinfo = userService.getUserByEmail(email);
        if(userinfo == null){
            return Result.fail(-2, "不存在该用户");
        }

        browseService.add(userinfo.getEmail(), product.getProductId());

        return Result.success(200, "添加成功");
    }

    /**
     *  删除商品浏览记录
     * @param email
     * @param productId
     * @return
     */
    @RequestMapping("/del")
    public Result delFavorite(String email, Long productId){
        System.out.println("删除商品浏览记录");

        if( productId <= 0 ){
            return Result.fail(-1, "无效参数");
        }

        User userinfo = userService.getUserByEmail(email);
        if(userinfo == null){
            return Result.fail(-2, "不存在该用户");
        }

        if(browseService.del(userinfo.getEmail(), productId) == 0){

            return Result.fail(-3, "删除失败");
        }

        return Result.success(200, "删除成功");
    }

    /**
     *  返回用户浏览商品列表
     * @param email
     * @return
     */
    @RequestMapping("/getProList")
    public Result getProList(String email){
        System.out.println("返回用户浏览商品列表");

//         根据用户的邮箱查找用户浏览商品列表，得到收藏的商品id的集合
        User userinfo = userService.getUserByEmail(email);
        if(userinfo == null){
            return Result.fail(-1, "用户未登录或已经登录");
        }
        List<Long> productIdList = browseService.getProList(userinfo.getEmail());

        // 根据得到的商品id集合，查找商品，添加至商品列表并返回
        List<Product> products = new ArrayList<>();
        for(Long productId : productIdList){
            products.add(productService.getProById(productId));
        }

        return Result.success(200, products);
    }
}
